package com.icloud.common.web.util;

import cn.hutool.core.util.StrUtil;
import com.icloud.common.core.api.CommonResult;
import com.icloud.common.core.api.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Http相关公共工具
 */
@Slf4j
@Component
public class HttpUtil {
    //默认语言
    private static final String DEFAULT_LANGUAGE = "en-us";

    /**
     * 获取客户端传递的语言代码(默认英文)
     */
    public static String getLanguage() {
        //获取request实例
        HttpServletRequest request = IpUtil.getRequest();
        if(request == null) {
            return DEFAULT_LANGUAGE;
        }
        //从头部获取客户端传递的语种信息
        String lang = request.getHeader("lang");
        if(StrUtil.isBlank(lang)) {
            lang = DEFAULT_LANGUAGE;
        }
        return lang;
    }

    /**
     * 内部feign接口数据获取
     */
    public static <T> T getFeignData(CommonResult<T> restResult) {
        if (ResultCode.SUCCESS.getCode() == restResult.getCode() && restResult.getData() != null) {
            return restResult.getData();
        }
        return null;
    }

    /**
     * 根据当前地域信息获取多语言字段名(如：zh-cn -> zh_cn)
     */
    public static String getColumnNameByLang() {
        String lang = getLanguage();
        return lang.replace("-", "_");
    }

    /**
     * 获取指定地域对应的字段值
     * @param prefix 字段前缀
     * @param map 包含各种语言的数据map
     * @param isCameCase 字段是否使用驼峰形式
     */
    public static String getLangColumnValue(String prefix, Map<String, Object> map, boolean isCameCase) {
        String lang = getLanguage();
        String columnName = StrUtil.isNotEmpty(prefix) ? prefix + "_" : "";
        switch (lang) {
            case "zh-cn":
                columnName = columnName + "simple_chinise";
                break;
            case "zh-tw":
                columnName = columnName + "traditional_chinise";
                break;
            case "ms-my":
                columnName = columnName + "malay";
                break;
            default:
                columnName = columnName + "english";
                break;
        }
        if(isCameCase) {
            //将字段转为小驼峰
            columnName = StrUtil.toCamelCase(columnName);
        }
        return (String) map.getOrDefault(columnName, null);
    }
}
